package com.bio.utils;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bio.entity.user.User;

public class AccountFilter implements Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
		HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
		
		User user = (User)httpServletRequest.getSession().getAttribute(Constants.Session.LOGIN_USER);
		if (!isExcludePages(httpServletRequest.getRequestURI())) {
			if (user == null) {
				httpServletResponse.setCharacterEncoding("UTF-8");
				String failInfo = new String("您还没有登录".getBytes("UTF-8"),"ISO8859-1");
				httpServletResponse.sendRedirect(httpServletRequest
						.getContextPath()
						+ "/system.jsp?failInfo="+failInfo);
				return;
			}
		}
		filterChain.doFilter(servletRequest, servletResponse);

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

	private boolean isExcludePages(String url) {
		return url.indexOf("verifyCode.jsp") != -1
				|| url.indexOf("index.jsp") != -1
				|| url.indexOf("system.jsp") != -1
				|| url.indexOf("login.action") != -1
				|| url.indexOf("regist.action") != -1
				|| url.indexOf("findPassword.jsp") != -1
				|| url.indexOf("findPassword") != -1
				|| url.indexOf("toResetPassword") != -1
				|| url.indexOf("resetPassword.jsp") != -1
				|| url.indexOf("regist.jsp") != -1 || url.endsWith(".css")
				|| url.endsWith(".js") || url.endsWith(".gif")
				|| url.endsWith(".jpg") || url.endsWith(".png")|| url.endsWith(".xls")
				|| url.endsWith("medicalManager/") || url.endsWith("medicalManager");
	}
}
